import Vue from "vue";
import Router from "vue-router";
import MiniFox from "@/util/minifox";
import auth from "@/util/auth";
import store from "@/store";
import table from "@/router/table";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
const TOKEN_KEY = "secureclienttoken";
NProgress.configure({ showSpinner: table.showSpinner });
Vue.use(Router);
let router = new Router(table);

router.beforeEach((to, from, next) => {
  if (!to.name || !to.meta) {
    next({ name: "Warn", params: { code: "404" } });
    return;
  }
  let gonext = () => {
    NProgress.start();
    next();
  };

  store.dispatch('init').then(()=>{

    if (to.meta.allowAnonymous) {
      gonext();
      return;
    } else {
      if (store.state.token){
        gonext();
      }
      else{
        let uri = new MiniFox.Uri(location.href);
        if (uri.params[TOKEN_KEY]){
          store.commit('setToken', uri.params[TOKEN_KEY]);
          store.dispatch('sessionInit').then(()=>{
            gonext();
          });
        }
        else{
          store.dispatch('getToken').then((response)=>{
            if (response.success){
              store.dispatch('sessionInit').then(()=>{
                gonext();
              });
            }
            else
              auth.gotoSSO();
          });
        }
      }
    }
  });
});

router.afterEach((to) => {
  if (to.meta)
    if (to.meta.title) {
      window.document.title = to.meta.title;
    } else {
      let route = to.matched.singleOrDefault(
        (item) => item.name.toLowerCase() == to.name.toLowerCase()
      );
      window.document.title = route.meta.title;
    }
  NProgress.done();
});

export default router;
